<template>
  <section class="padding EndWaybillList">
    <el-card>
      <div slot="header" class="clearfix relative">
        <span class="title-icon">常用派送地址</span>
        <div class="absolute add-btn-box">
          <el-button
            type="success"
            size="mini"
            icon="el-icon-plus"
            @click="addInfo"
          >
            新增
          </el-button>
        </div>
      </div>

      <el-row :gutter="10">
        <el-col
          v-for="(item, index) in pickupInfo"
          :key="index"
          :md="24"
          :lg="12"
        >
          <div
            class="my-profile-info-box flex justify-between"
            :class="{ 'border-green': item.defaultValue == 1 }"
          >
            <div class="flex align-start" style="width: 90%">
              <div class="margin-right flex-sub text-cut">
                <div class="margin-bottom text-cut">
                  公司名/个人：{{ item.customerDeliveryCompany }}
                </div>
                <div class="margin-bottom">
                  联系人：{{ item.customerDeliveryAddressAttn }}
                </div>
                <div class="margin-bottom text-cut">
                  地址1：{{ item.address }}
                </div>
                <div class="margin-bottom">城市：{{ item.city }}</div>
                <div>邮编：{{ item.zipCode }}</div>
              </div>
              <div class="flex-sub text-cut">
                <div class="margin-bottom">
                  国家：{{
                    $store.state.public.publicData.countryMap[item.countryId]
                  }}
                </div>
                <div class="margin-bottom">
                  电话：{{ item.customerDeliveryAddressPhone }}
                </div>

                <div class="margin-bottom text-cut">
                  地址2：{{ item.address2 }}
                </div>
                <div class="margin-bottom">省：{{ item.state }}</div>
                <div>邮箱：{{ item.customerDeliveryAddressEmail }}</div>
              </div>
            </div>
            <div
              class="flex justify-end flex-direction text-right"
              style="width: 10%"
            >
              <div class="text-lg">
                <el-tooltip content="编辑" effect="light" placement="top-end">
                  <i
                    class="el-icon-edit-outline pointer margin-right"
                    @click="editInfo(index)"
                  />
                </el-tooltip>
                <el-tooltip content="删除" effect="light" placement="top-end">
                  <i class="el-icon-delete pointer" @click="delInfo(index)" />
                </el-tooltip>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog
      title="新增常用派送地址"
      width="36%"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="ruleForm"
        :rules="rules"
        label-position="left"
        label-width="120px"
        size="mini"
        :model="form"
        class="padding-lr-40"
      >
        <el-form-item prop="customerDeliveryCompany">
          <div slot="label">公司名:</div>
          <el-input
            v-model="form.customerDeliveryCompany"
            placeholder="请填写公司名"
            clearable
          />
        </el-form-item>

        <el-form-item prop="customerDeliveryAddressAttn">
          <div slot="label">联系人:</div>
          <el-input
            v-model="form.customerDeliveryAddressAttn"
            placeholder="请填写联系人"
            clearable
          />
        </el-form-item>
        <el-form-item prop="customerDeliveryAddressPhone">
          <div slot="label">联系方式:</div>
          <el-input
            v-model="form.customerDeliveryAddressPhone"
            placeholder="请填写联系方式"
            clearable
          />
        </el-form-item>
        <el-form-item prop="customerDeliveryAddressEmail">
          <div slot="label">邮箱:</div>
          <el-input
            v-model="form.customerDeliveryAddressEmail"
            placeholder="请填写联系方式"
            clearable
          />
        </el-form-item>
        <el-form-item prop="address">
          <div slot="label">详细地址1:</div>
          <el-input
            v-model="form.address"
            placeholder="请填写详细地址"
            clearable
          />
        </el-form-item>
        <el-form-item prop="address2">
          <div slot="label">详细地址2:</div>
          <el-input
            v-model="form.address2"
            placeholder="请填写详细地址"
            clearable
          />
        </el-form-item>
        <el-form-item prop="city">
          <div slot="label">城市:</div>
          <el-input v-model="form.city" placeholder="请填写城市" clearable />
        </el-form-item>

        <el-form-item
          v-if="form.countryId && [329, 332, 339].includes(form.countryId)"
          label="州/省："
          prop="state"
        >
          <el-select v-model="form.state" filterable placeholder="请选择">
            <el-option
              v-for="item in stateMap[form.countryId]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-else prop="state">
          <div slot="label">州/省:</div>
          <el-input
            v-model="form.state"
            :maxlength="textLength"
            placeholder="请填写州/省"
            clearable
          />
        </el-form-item>

        <el-form-item prop="countryId">
          <div slot="label">国家:</div>

          <el-select
            v-model="form.countryId"
            filterable
            placeholder="请选择"
            @change="changeCountry"
          >
            <el-option
              v-for="(item, value) in $store.state.public.publicData.countryMap"
              :key="value"
              :label="item"
              :value="parseInt(value)"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="zipCode">
          <div slot="label">邮编:</div>
          <el-input v-model="form.zipCode" clearable placeholder="请填写邮编" />
        </el-form-item>
        <!-- <el-form-item prop="defaultValue">
          <div slot="label">是否默认:</div>
          <el-radio-group v-model="form.defaultValue">
            <el-radio :label="parseInt(1)">是</el-radio>
            <el-radio :label="parseInt(0)">否</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm')">{{
          editType == 'add' ? '立即创建' : '保存'
        }}</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
// import TableModule from '@/components/TableModule'
import { getToken } from '@/utils/auth'
import { getState } from '@/utils/getState'
import {
  customerdeliveryaddressList,
  customerdeliveryaddressSave,
  customerdeliveryaddressDelete,
} from '@/api/myProfile'
export default {
  name: 'ShippingAddress',
  components: {
    // TableModule
  },
  data() {
    return {
      stateMap: getState(),
      editType: 'add',
      textLength: 30,
      dialogFormVisible: false,
      form: {
        id: '',
        customerDeliveryCompany: '',
        customerDeliveryAddressAttn: '',
        customerDeliveryAddressPhone: '',
        customerDeliveryAddressEmail: '',
        address: '',
        address2: '',
        city: '',
        state: '',
        countryId: '',
        zipCode: '',
      },

      pickupInfo: [],

      rules: {
        customerDeliveryCompany: [
          { required: true, message: '请填写公司名', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9_\，\,\.\/\-\s\!\@\#\$\%\^\&\*\(\)]*$/,
            message: '请填写英文或者数字',
          },
        ],
        countryId: [
          { required: true, message: '请选择国家', trigger: 'change' },
        ],
        customerDeliveryAddressAttn: [
          { required: true, message: '请填写联系人', trigger: 'blur' },
        ],
        customerDeliveryAddressPhone: [
          { required: true, message: '请填写联系方式', trigger: 'blur' },
        ],
        customerDeliveryAddressEmail: [
          { required: false, message: '请填写邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change'],
          },
        ],
        // zipCode: [{ required: true, message: '请填写邮编', trigger: 'blur' }],
        address: [
          { required: true, message: '请填写地址', trigger: 'blur' },
          {
            min: 1,
            max: 35,
            message: '长度在 1 到 35 个字符',
            trigger: 'blur',
          },
        ],
        address2: [
          { required: false, message: '请填写地址', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '长度在 1 到 30 个字符',
            trigger: 'blur',
          },
        ],
        state: [{ required: true, message: '请填写省', trigger: 'change' }],
        city: [{ required: true, message: '请填写城市', trigger: 'change' }],

        eori: [{ required: true, message: '请填写EORI', trigger: 'blur' }],
        vat: [{ required: true, message: '请填写VAT', trigger: 'blur' }],
        defaultValue: [
          { required: true, message: '请选择是否默认', trigger: 'change' },
        ],
      },
    }
  },
  mounted() {
    // this.fn()
    this.init()
    const _this = this
    this.rules.zipCode = [
      { required: true, message: '请填写邮编' },
      {
        validator: (rule, value, cb) => {
          const reg1 = /^((\d{5})*(-\d{4})|(\d{5}))$/;
          if (parseFloat(_this.form.countryId) === 329 && !reg1.test(value)) {
            cb(new Error('格式错误，美国邮编请填入XXXXX或者XXXXX-XXXX'))
          } else {
            cb()
          }
        },
        trigger: 'blur',
      },
    ]
  },
  methods: {
    async init() {
      const data = await customerdeliveryaddressList({
        authorization: getToken(),
      })
      this.pickupInfo = data
      this.$store.dispatch('app/toggleDialog', false)
    },
    addInfo() {
      if (this.pickupInfo.length >= 30) {
        this.dialogFormVisible = false
        this.$message.error('派送地址上限30个')
      } else {
        this.editType = 'add'
        this.dialogFormVisible = true
        this.form = {}
        this.textLength = 30
      }
    },
    editInfo(index) {
      this.editType = 'edit'
      this.dialogFormVisible = true
      this.form = this.pickupInfo[index]
      console.log(11, this.form.countryId)
      if (
        this.form.countryId === 339 ||
        this.form.countryId === 329 ||
        this.form.countryId === 332
      ) {
        this.textLength = 3
      } else {
        this.textLength = 30
      }
    },
    changeCountry() {
      if (
        this.form.countryId === 339 ||
        this.form.countryId === 329 ||
        this.form.countryId === 332
      ) {
        this.textLength = 3
      } else {
        this.textLength = 30
      }
    },
    async saveInfo() {
      this.$store.dispatch('app/toggleDialog', true)
      const data = await customerdeliveryaddressSave(this.form)
      if (data.code === 200) {
        this.$message({
          message: '保存成功',
          type: 'success',
        })
        this.init()
        this.dialogFormVisible = false

        setTimeout(() => {
          this.$refs['ruleForm'].resetFields()
          this.form = {
            id: '',
            customerDeliveryCompany: '',
            customerDeliveryAddressAttn: '',
            customerDeliveryAddressPhone: '',
            address: '',
            city: '',
            state: '',
            countryId: '',
            zipCode: '',
          }
        }, 1000)
      } else {
        this.$message.error(data.message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    delInfo(index) {
      this.$confirm('确认删除？')
        .then((_) => {
          this.$store.dispatch('app/toggleDialog', true)
          customerdeliveryaddressDelete(this.pickupInfo[index].id).then(
            (res) => {
              if (res.code === 200) {
                this.$message({
                  message: '已删除',
                  type: 'success',
                })
                this.init()
              } else {
                this.$store.dispatch('app/toggleDialog', false)
                this.$message.error(res.message)
              }
            }
          )
        })
        .catch((_) => {})
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (
            (this.form.countryId === 339 ||
              this.form.countryId === 329 ||
              this.form.countryId === 332) &&
            this.form.state.length > 3
          ) {
            this.$message.error('省州长度不可以大于3')
            return false
          }

          this.saveInfo()
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      if (this.$refs[formName]) this.$refs[formName].resetFields()
      this.form = {
        id: '',
        customerDeliveryCompany: '',
        customerDeliveryAddressAttn: '',
        customerDeliveryAddressPhone: '',
        address: '',
        city: '',
        state: '',
        countryId: '',
        zipCode: '',
      }
    },
  },
}
</script>

<style scoped>
.EndWaybillList >>> .el-textarea__inner {
  min-height: 60px !important;
}
</style>

<style lang="scss" scoped>
.item {
  position: absolute;
  right: -25px;
  top: 3px;
  font-size: 20px;
}
.add-btn-box {
  right: 0;
  top: -6px;
}
</style>
